package utils

import (
	"alertmanagerWebhook/config"
	"alertmanagerWebhook/global"
	"fmt"
	"strings"
)

func SplitCombinedAlerts(content string) ([]*config.DingDingMarkdown, []*config.QyWeChatMarkdown) {
	var dingMessages []*config.DingDingMarkdown
	var wechatMessages []*config.QyWeChatMarkdown
	projectName := global.Config.System.ProjectName
	marker := projectName + "--"

	// 统一处理消息中的换行和空格
	content = strings.ReplaceAll(content, "  \n", "\n")
	content = strings.TrimSpace(content)

	// 按项目标记分割消息
	rawParts := strings.Split(content, marker)

	for _, part := range rawParts {
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}

		// 提取告警类型和内容
		lines := strings.SplitN(part, "\n", 2)
		if len(lines) < 2 {
			continue
		}

		alertType := strings.TrimSpace(lines[0])
		alertContent := strings.TrimSpace(lines[1])

		if alertType == "" || alertContent == "" {
			continue
		}

		// 处理内容中可能存在的多余空行
		alertContent = strings.ReplaceAll(alertContent, "\n\n", "\n")

		// 构建完整消息
		fullContent := marker + alertType + "\n" + alertContent

		// 钉钉消息：确保每条消息都包含@信息
		dingMsg := config.NewDingDingMarkdown(
			global.Config.System.ProjectName,
			fullContent,
			global.Config.DingDing.AtMobiles,
		)
		// 如果内容中没有@信息，手动添加
		if !strings.Contains(fullContent, "@") && len(global.Config.DingDing.AtMobiles) > 0 {
			dingMsg.Markdown.Text += "\n\n@" + strings.Join(global.Config.DingDing.AtMobiles, " @")
		}
		dingMessages = append(dingMessages, dingMsg)

		// 企业微信消息：确保每条消息都包含@信息
		wechatMsg := config.NewQyWeChatMarkdown(
			fullContent,
			global.Config.QyWeChat.AtMobiles,
		)
		// 如果内容中没有@信息，手动添加
		if !strings.Contains(fullContent, "@") && len(global.Config.QyWeChat.AtMobiles) > 0 {
			// 转换手机号为userID格式
			userIDs, err := ConvertMobilesToUserIDs(global.Config.QyWeChat.AtMobiles)
			if err != nil {
				global.Logger.Errorf("转换手机号到userid失败: %v", err)
				// 转换失败时使用手机号
				wechatMsg.Markdown.Content += "\n\n@" + strings.Join(global.Config.QyWeChat.AtMobiles, " @")
			} else {
				// 使用userID格式 <@userid>
				for _, userID := range userIDs {
					wechatMsg.Markdown.Content += fmt.Sprintf(" <@%s>", userID)
				}
			}
		}
		wechatMessages = append(wechatMessages, wechatMsg)
	}
	return dingMessages, wechatMessages
}
